package com.da.javatest.thread.other.semaphore;

import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

public class MicrowaveOvenPool {

    private List<MicrowaveOven> microwaveOvens;

    private Semaphore semaphore;

    public MicrowaveOvenPool(int size, List<MicrowaveOven> microwaveOvens) {
        this.microwaveOvens = new Vector<>(microwaveOvens);
        this.semaphore = new Semaphore(size);
    }

    public Food exec(Function<MicrowaveOven, Food> func) {
        MicrowaveOven microwaveOven = null;
        try {
            semaphore.acquire();
            microwaveOven = microwaveOvens.remove(0);
            return func.apply(microwaveOven);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            microwaveOvens.add(microwaveOven);
            semaphore.release();
        }
        return null;
    }

    public static void main(String[] args) {
        List<MicrowaveOven> microwaveOvens = Arrays.asList(new MicrowaveOven("烤箱1号"), new MicrowaveOven("烤箱2号"));
        MicrowaveOvenPool microwaveOvenPool = new MicrowaveOvenPool(2, microwaveOvens);
        new Thread(()-> microwaveOvenPool.exec(microwaveOven -> microwaveOven.warm(new Food("土豆", 1)))).start();
        new Thread(()-> microwaveOvenPool.exec(microwaveOven -> microwaveOven.warm(new Food("面包", 2)))).start();
        new Thread(()-> microwaveOvenPool.exec(microwaveOven -> microwaveOven.warm(new Food("鸡腿", 2)))).start();
        new Thread(()-> microwaveOvenPool.exec(microwaveOven -> microwaveOven.warm(new Food("鸭腿", 1)))).start();
    }

}